package com.tap.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.annotation.Resource;
import java.util.Random;

@Configuration
public class MailUtil {

    @Resource
    private JavaMailSender javaMailSender;

    private SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

    @Value("${spring.mail.username}")
    private String from;

    public String sendMail(String email){
        simpleMailMessage.setSubject("千峰教育注册验证码！");
        StringBuffer code = new StringBuffer();
        Random random = new Random();
        for(int i = 0;i < 6;i++){
            code.append(random.nextInt(10));
        }
        simpleMailMessage.setText("打死都不要告诉别人:" + code.toString());
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(email);

        try {
            javaMailSender.send(simpleMailMessage);   //发送验证码给注册用户
            return code.toString();                   //返回给后台用于保存验证码信息
        } catch (MailException e) {
            e.printStackTrace();
        }
        return null;                                   //发送失败，不保存
    }
}
